const express = require('express')
const app = express()

const axios = require('axios');


const server = require('http').createServer(app);
const io = require("socket.io")(server, {
    cors: {
        // origin: "http://127.0.0.1:8080",
        origin: "*",
        methods: ["GET", "POST"]
    }
});


// io.set('origins', '*:*');
// io.set("Access-Control-Allow-Origin", "*");
// io.set("Access-Control-Allow-Headers", "X-Requested-With,Content-type,token");
// io.set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
// io.set("X-Powered-By", ' 3.2.1');
// io.set("Content-Type", "application/json;charset=utf-8");

const connObj = require("./sqlconn")
const echartsData = require("./food/echarts/caipin")
const doToken = require("./token")

let env = process.env.NODE_ENV || "dev";
const port_listen = connObj.getconn(env).port_listen;
console.log(connObj.getconn(env))
const bodyParser = require('body-parser');

class User {
    constructor(token, username, password) {
        this.token = token;
        this.username = username;
        this.password = password;
        this.id = "";
        this.email = "";
        this.expires = "";
        this.fabu = "";
        this.level = "";
        this.remark = "";
        this.version = "";
    }

    getUser(callback) {

        let results;
        connection.query(`select * from yonghu where username = '${this.username}' and password = '${this.password}'`, function (error, result, fields) {
            results = result;
            connection.query(`select * from version order by id desc limit 1`, function (error2, resultsVersion, fields2) {
                if (results.length) {
                    this.id = results[0].id;
                    this.email = results[0].email;
                    this.expires = results[0].expires;
                    this.fabu = results[0].fabu;
                    this.level = results[0].level;
                    this.token = results[0].token;
                    this.version = resultsVersion[0].version;
                    return callback(this)
                } else {
                    return callback(null);
                }
            })
        })
        // if (this.token) {
        //     results = await connection.query(`select * from yonghu where token = '${this.token}'`)
        // } else {
        //     try {
        //         console.log(connObj)
        //         results = await connObj.query(`select * from yonghu where username = '${this.username}' and password = '${this.password}'`)
        //         // results = await connection.query(`select * from yonghu`)
        //     } catch (error) {

        //         debugger
        //     }

        // }
        // connObj.query(`select * from yonghu where username = '${this.username}' and password = '${this.password}'`)
        // let resultsVersion = await connObj.query(`select * from version order by id desc limit 1`)
        // if (results.length) {
        //     this.id = results[0].id;
        //     this.email = results[0].email;
        //     this.expires = results[0].expires;
        //     this.fabu = results[0].fabu;
        //     this.level = results[0].level;
        //     this.token = results[0].token;
        //     this.version = resultsVersion[0].version;
        //     return callback(this)
        // } else {
        //     return callback(null);
        // }
    }

    // async getUser(callback) {

    //     let results;
    //     if (this.token) {
    //         results = await connection.query(`select * from yonghu where token = '${this.token}'`)
    //     } else {
    //         try {
    //             console.log(connObj)
    //             results = await connObj.query(`select * from yonghu where username = '${this.username}' and password = '${this.password}'`)
    //             // results = await connection.query(`select * from yonghu`)
    //         } catch (error) {

    //             debugger
    //         }

    //     }
    //     let resultsVersion = await connObj.query(`select * from version order by id desc limit 1`)
    //     if (results.length) {
    //         this.id = results[0].id;
    //         this.email = results[0].email;
    //         this.expires = results[0].expires;
    //         this.fabu = results[0].fabu;
    //         this.level = results[0].level;
    //         this.token = results[0].token;
    //         this.version = resultsVersion[0].version;
    //         return callback(this)
    //     } else {
    //         return callback(null);
    //     }
    // }
}
// 配置body-parser模块
app.use(bodyParser.urlencoded({
    extended: false,
}));

app.use(bodyParser.json())
var mysql = require('mysql');
const { log } = require('console');
const { url } = require('inspector');
const { response } = require('express');
// const { delDiancan } = require('../src/utils/api');

var connection = mysql.createConnection(connObj.getconn(env));
try {
    connection.connect();
    console.log("mysql连接成功", connection)
} catch (error) {
    console.log("mysql连接报错", error)
}


function getUser(req, res) {
    connection.query("select *,DATE_FORMAT(tjtime, '%Y-%m-%d %H:%i:%s') as shijian from user", function (error, results, fields) {
        if (results.length) {
            let caipinTotal, caipinMonth, caipinWeek;
            caipinTotal = echartsData.getCaipinTotalObj(results, "total");
            caipinMonth = echartsData.getCaipinTotalObj(results, "month");
            caipinWeek = echartsData.getCaipinTotalObj(results, "week");
            res.send({
                caipinTotal: caipinTotal,
                caipinMonth: caipinMonth,
                caipinWeek: caipinWeek,
            })
        }
    })
}
// getUser()
// return;



app.all("/*", function (req, res, next) {
    // 跨域处理
    // DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range
    res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-type,token");
    res.header("Access-Control-Allow-Headers", "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,token,baseUrl");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", '3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");

    // res.header("Access-Control-Allow-Origin", "*");
    // res.header('Access-Control-Allow-Headers', 'Content-type,token');
    // res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH");
    // res.header('Access-Control-Max-Age',1728000);//预请求缓存20天
    // res.header("Access-Control-Allow-Headers","token")

    if (req.headers.accept == "application/json" || req.headers.accept == "application/x-www-form-urlencoded") {
        if (req.headers.token || req.originalUrl == "/user/login") {
            next(); // 执行下一个路由
        } else {
            res.send({
                code: -1,
                msg: "token为空，请重新登录",
                data: {
                    token: req.headers.token,
                }
            })
        }
    } else {
        next();
    }


})
app.post('/ceshi', (req, res) => {
    console.log("/")
    res.send('Hello World!' + getLocalIP())
})
app.post("/user/getEchartsData", (req, res) => {
    connection.query("select *,DATE_FORMAT(tjtime, '%Y-%m-%d %H:%i:%s') as shijian from user", function (error, results, fields) {
        if (results.length) {
            let caipinTotal, caipinMonth, caipinWeek;
            caipinTotal = echartsData.getCaipinTotalObj(results, "total");
            caipinMonth = echartsData.getCaipinTotalObj(results, "month");
            caipinWeek = echartsData.getCaipinTotalObj(results, "week");
            res.send({
                caipinTotal: caipinTotal,
                caipinMonth: caipinMonth,
                caipinWeek: caipinWeek,
            })
        }
    })
})
app.post("/user/getEchartsDataMyself", (req, res) => {
    let token = req.headers.token;
    let obj = doToken.verifytoken(token)
    let username = obj.username
    connection.query(`select *,DATE_FORMAT(tjtime, '%Y-%m-%d %H:%i:%s') as shijian from user where username='${username}'`, function (error, results, fields) {
        if (results.length) {
            let caipinTotal, caipinMonth, caipinWeek;
            caipinTotal = echartsData.getCaipinTotalObj(results, "total");
            caipinMonth = echartsData.getCaipinTotalObj(results, "month");
            caipinWeek = echartsData.getCaipinTotalObj(results, "week");
            res.send({
                caipinTotal: caipinTotal,
                caipinMonth: caipinMonth,
                caipinWeek: caipinWeek,
            })
        }
    })
})
app.post("/user/updateUser", (req, res) => {
    let email = req.body["email"];
    let level = req.body["level"];
    let token = req.headers.token;
    let obj = doToken.verifytoken(token)

    connection.query(`update yonghu set email='${email}',level='${level}' where id = '${obj.id}'`, function (error, updateResults) {
        // let results;
        // connection.query(`select * from yonghu where username = '${obj.username}' and password = '${obj.password}'`, function (error, result, fields) {
        //     results = result;
        //     connection.query(`select * from version order by id desc limit 1`, function (error2, resultsVersion, fields2) {
        //         let user = {};
        //         let token = "";
        //         if (results.length) {
        //             user.id = results[0].id;
        //             user.email = results[0].email;
        //             user.expires = results[0].expires;
        //             user.fabu = results[0].fabu;
        //             user.level = results[0].level;
        //             user.token = results[0].token;
        //             user.version = resultsVersion[0].version;
        //             token = doToken.gettoken(user)
        //             // token = user
        //         }

        //         res.send({
        //             code: 200,
        //             msg: "",
        //             data: {
        //                 token: token,
        //             }
        //         })
        //     })
        // })
        res.send({
            code: 200,
            msg: "",
            data: {
                token: "",
            }
        })
    })

})

app.post("/user/checkVersion", (req, res) => {
    // let token = req.header.token;
    // if(!token){
    //     return;
    // }
    let obj = req.body

    connection.query("select * from version order by id desc limit 1", function (error, results) {
        let version = results[0].version;
        if (version != obj.version) {
            res.send({
                code: -1,
                msg: "有新版本发布，请重新登录。"
            })
        }
        else {
            res.send({
                code: 200,
                msg: ""
            })
        }
    })
})

app.post("/user/getUserInfo", (req, res) => {
    let token = req.headers.token;
    try {
        let obj = doToken.verifytoken(token)
        res.send({
            code: 200,
            msg: "",
            data: {
                token: "",
                user: obj
            }
        })
    } catch (error) {
        res.send({
            code: 200,
            msg: "",
            data: {
                token: "",
                user: ""
            }
        })
    }

})
app.post("/user/login", (req, res) => {
    let username = req.body["username"];
    let password = req.body["password"];

    let results;
    connection.query(`select * from yonghu where username = '${username}' and password = '${password}'`, function (error, result, fields) {
        results = result;
        connection.query(`select * from version order by id desc limit 1`, function (error2, resultsVersion, fields2) {
            let user = {};
            let token = "";
            if (results.length) {
                user.username = results[0].username;
                user.id = results[0].id;
                user.email = results[0].email;
                user.expires = results[0].expires;
                user.fabu = results[0].fabu;
                user.level = results[0].level;
                user.token = results[0].token;
                user.version = resultsVersion[0].version;
                token = doToken.gettoken(user)
                // token = user
            }

            res.send({
                code: 200,
                msg: "",
                data: {
                    token: token,
                }
            })
        })
    })

    // new User("", username, password).getUser(user1 => {
    //     let token = doToken.gettoken(user1)
    //     if (!user1) {
    //         token = user1
    //     }
    //     res.send({
    //         code: 200,
    //         msg: "",
    //         data: {
    //             token: token,
    //         }
    //     })
    // })
})

app.post('/admin/addFood', (req, res) => {
    // res.send('Hello World!123')
    let foodName = req.body["foodName"]
    connection.query(`insert into caipin values(null,'${foodName}','是','')`, function (error, results, fields) {
        try {
            if (error) throw error;
            res.send(results)
        } catch (error) {
            console.log("出错1")
        }

    });
})

app.post('/admin/delFood', (req, res) => {
    // res.send('Hello World!123')
    let foodName = req.body["foodName"]
    connection.query(`delete from caipin where caipin = '${foodName}'`, function (error, results, fields) {
        try {

            if (error) throw error;
            res.send(results)
        } catch (error) {
            console.log("出错2")
        }

    });
})

app.post('/admin/fabu', (req, res) => {
    // res.send('Hello World!123')
    let nowDay = getTimeByTimeZone(8).Format("yyyy-MM-dd");
    let nowTime = req.body["nowTime"]
    let startTime = req.body["startTime"]
    let endTime = req.body["endTime"]
    let caipin = req.body["caipinSelectArr"]
    let faburen = req.body["faburen"]
    let remark = req.body["remark"]
    console.log(`${faburen}发布了信息`)
    connection.query(`insert into detail values(null,'${nowDay}','${startTime}','${endTime}','${caipin}','${faburen}','${nowTime}','${remark}')`, function (error, results, fields) {
        try {
            if (error) throw error;
            checkFabuToClient(io, "new");
            res.send(results)
        } catch (error) {
            console.log("出错3")
        }

    });
})
app.post('/admin/delFabu', (req, res) => {
    // res.send('Hello World!123')
    let nowDay = getTimeByTimeZone(8).Format("yyyy-MM-dd");
    let faburen = req.body["faburen"]
    console.log(`${faburen}删除了今日发布信息`)
    connection.query(`delete from detail where DATE_FORMAT(riqi,'%Y-%m-%d') = '${nowDay}' `, function (error, results, fields) {
        try {
            if (error) throw error;
            res.send(results)
        } catch (error) {
            console.log("出错4")
        }

    });
})
function toJava(req, res) {
    console.log(req.headers["baseurl"])
    port = req.headers["baseurl"].split(":")[2].split("/")[0];
    newPort = parseInt(port) + 1;
    baseurl = req.headers["baseurl"].replace(port, newPort);
    // baseurl = baseurl.replace("//","/");

    // let baseurl = req.headers["baseurl"];
    // baseurl = baseurl.replace("localhost:3000","3.226.17.158:3003");
    baseurl = baseurl.replace("3.226.17.158", "127.0.0.1");
    req.body["user"] = doToken.verifytoken(req.headers["token"]);
    console.log("tojava的baseurl是", baseurl + req.url);
    console.log(new Date().Format("yyyy-MM-dd hh:mm:ss").toString())
    axios.post(baseurl + req.url, req.body, {
        headers: { 'Content-Type': 'application/json;charset=utf8', 'lang': 'zh_CN' }
    }).then(response => {
        console.log(response)
        res.send(response.data)
    })
}
app.post('/book/*', (req, res) => {
    toJava(req, res)
})
app.post('/club/getActivityList', (req, res) => {
    toJava(req, res)
})
app.post('/club/joinActivity', (req, res) => {
    toJava(req, res)
})
app.post('/club/getClubList', (req, res) => {
    toJava(req, res)
})
app.post('/club/getYonghuByClub', (req, res) => {
    toJava(req, res)
})
app.post('/club/getClubinfoByUser', (req, res) => {
    toJava(req, res)
})
app.post('/club/addClub', (req, res) => {
    toJava(req, res)
})
app.post('/club/addActivity', (req, res) => {
    toJava(req, res)
})

function updateProjections(res, obj, str) {
    connection.query(`delete from club_projected_information_person where username='${obj.username}'`, function (error1, results1, fields1) {
        connection.query(str, function (error2, results2, fields2) {
            if (results2.affectedRows !== 1) {
                res.send({
                    code: 0,
                    msg: '提交预测信息成功'
                })

            } else {
                // console.log(`没有添加活动信息`)
                res.send({
                    code: -2,
                    msg: '提交预测信息失败'
                })
            }
        })
    })

}

// 填写活动预测信息
app.post('/club/submitProjections', (req, res) => {
    console.log(req);
    let token = req.headers.token;
    let obj = doToken.verifytoken(token)
    let list = req.body.projectedList
    let sql = `insert into club_projected_information values`
    let str = ''
    if (list.length) {
        for (let index = 0; index < list.length; index++) {
            let el = list[index]
            let username = el["userName"] || obj.username
            let red_team = el["redTeam"]
            let blue_team = el["blueTeam"]
            let match_id = el["matchId"]
            let projected_red_score = el["projectedRedScore"]
            let projected_blue_score = el["projectedBlueScore"]
            let pre_match_comments = el["preMatchComments"] ? el["preMatchComments"] : ""
            let post_match_comments = el["postMatchComments"] ? el["postMatchComments"] : ""
            let best_pre_prediction = el["best_pre_prediction"] || 'null'
            let best_after_comments = el["best_after_comments"] || 'null'

            let commit_time = getTimeByTimeZone(8).Format("yyyy-MM-dd hh:mm:ss")

            str += `${index === 0 ? '' : ','}(null,${match_id},'${red_team}', '${blue_team}', ${projected_red_score}, ${projected_blue_score}, '${username}', '${pre_match_comments}', '${post_match_comments}', ${best_pre_prediction} , ${best_after_comments}, '${commit_time}',null)`

        }
    }
    sql += str
    console.log(sql);
    connection.query(sql, function (error, results, fields) {
        try {

            if (error) throw error;
            console.log(results);
            if (results.affectedRows !== 1) {
                // console.log(`成功添加活动信息`)
                updateProjections(res, obj, sql.replace('club_projected_information', 'club_projected_information_person'))

            } else {
                // console.log(`没有添加活动信息`)
                res.send({
                    code: -2,
                    msg: '提交预测信息失败'
                })
            }
        } catch (error) {
            console.log("出错11")
        }
    });

})

// 获取个人竞猜信息
app.post('/club/getProjectionsInfo', (req, res) => {
    let token = req.headers.token;
    let obj = doToken.verifytoken(token)
    let sql = `select * from club_projected_information_person where username = '${obj.username}' ORDER BY commit_time DESC LIMIT 10`
    console.log(sql);
    connection.query(sql, function (error, results, fields) {
        try {

            if (error) throw error;
            // console.log(results);
            // console.log(results.affectedRows);
            if (results.length !== 0) {
                // console.log(`成功添加活动信息`)
                res.send({
                    code: 0,
                    msg: '请求成功',
                    data: results
                })
            } else {
                // console.log(`没有添加活动信息`)
                res.send({
                    code: -2,
                    msg: '获取失败'
                })
            }
        } catch (error) {
            console.log("出错12")
        }
    });
})

// 获取公告
app.post('/user/getGonggao', (req, res) => {
    let token = req.headers.token;
    let obj = doToken.verifytoken(token)
    let getTime = getTimeByTimeZone(8).Format("yyyy-MM-dd hh:mm:ss")
    let sql = `select * from gonggao where startTime < '${getTime}' and endTime > '${getTime}' order by id desc`
    console.log(sql)
    connection.query(sql, function (error, results, fields) {
        try {

            if (error) throw error;
            if (results.length !== 0) {
                // console.log(`成功添加活动信息`)
                res.send({
                    code: 0,
                    msg: '请求成功',
                    data: results
                })
            } else {
                // console.log(`没有添加活动信息`)
                res.send({
                    code: -2,
                    msg: '获取失败'
                })
            }
        } catch (error) {
            console.log("出错13")
        }
    });
})

app.post('/club/getPersonRaceList', (req, res) => {
    connection.query("select * from club_projected_information_person", function (error, results, fields) {
        res.send({
            code: 0,
            msg: '请求成功',
            data: results
        })
    })
})

app.post('/club/getCommentList', (req, res) => {
    let matchId = req.body["matchId"]
    connection.query(`select * from club_projected_information_person where (pre_match_comments != '' or post_match_comments !='') and match_id=${matchId}`, function (error, results, fields) {
        res.send({
            code: 0,
            msg: '请求成功',
            data: results
        })
    })
})
// 获取比赛赛程

app.post('/club/getMatchSchedule', (req, res) => {
    // console.log(req);
    let token = req.headers.token;
    let obj = doToken.verifytoken(token)
    let sql = `select * from soccer_match `
    let getTime = getTimeByTimeZone(8).Format("yyyy-MM-dd hh:mm:ss")
    let time = new Date(getTime)
    let nowTime = time.getTime()  //当前时间
    connection.query(sql, function (error, results, fields) {
        try {

            if (error) throw error;
            let returnArr = []
            if (results.length !== 0) {
                // console.log(`成功添加活动信息`)
                results.map((item, index) => {
                    // console.log(item);
                    let matchTime = (new Date(item['match_time'])).getTime()  //比赛时间
                    //status:-1：未开始  0：正在进行 1：已完成 2：已完成24小时后
                    if (matchTime - nowTime > 0) {
                        item.status = -1   //未进行比赛
                    } else {

                        if (nowTime - matchTime < 7200000) {
                            item.status = 0   //比赛开始2小时内
                        }
                        else {
                            item.status = 1
                            if (nowTime - matchTime > 86400000) {
                                item.status = 2   //比赛已完成24小时
                            }
                        }
                    }
                    item.match_time = item.match_time.Format("yyyy-MM-dd hh:mm:ss")
                    returnArr.push(item)

                })
                console.log(returnArr);
                res.send({
                    code: 0,
                    msg: '请求成功',
                    data: returnArr
                })
            } else {
                // console.log(`没有添加活动信息`)
                res.send({
                    code: -2,
                    msg: '获取失败'
                })
            }
        } catch (error) {
            console.log("出错14")
        }
    });
})


app.post('/admin/addUser', (req, res) => {
    // res.send('Hello World!123')
    let username = req.body["username"]
    console.log(`准备添加${username}用户信息`)
    console.log(`insert into yonghu values(null,'${username}','123456','${username}@etekcity.com.cn','',null,'','','')`)
    connection.query(`insert into yonghu values(null,'${username}','123456','${username}@etekcity.com.cn','',null,'','','')`, function (error, results, fields) {
        try {

            if (error) throw error;
            if (results.affectedRows == 1) {
                console.log(`成功添加${username}用户信息`)
            } else {
                console.log(`没有添加${username}用户信息`)
            }
            res.send(results)
        } catch (error) {
            console.log("出错15")
        }

    });
})

app.post('/point/createPoint', (req, res) => {
    let token = req.headers.token;
    let obj = doToken.verifytoken(token)
    let username = obj.username

    let tableName = req.body["tableName"]
    let moduleName = req.body["moduleName"]
    let pageName = req.body["pageName"]
    let eventName = req.body["eventName"]
    let localTime = req.body["localTime"]
    let startTime = new Date().Format("yyyy-MM-dd hh:mm:ss").toString()
    if (eventName === "leave") {
        console.log("leave", startTime)
        let sql = `update event_${tableName} set leaveTime = '${startTime}',remark='leave' where username='${username}' and pageName='${pageName}' and eventName='load' order by id desc limit 1`
        console.log("sql", sql)
        connection.query(sql, function (error, results, fields) {
            try {

                if (error) throw error;
                // if (results.affectedRows == 1) {
                //     console.log(`成功修改`)
                // } else {
                //     console.log(`没有修改`)
                // }
                res.send(results)
            } catch (error) {
                console.log("出错16")
            }
        })
    }
    else {
        let sql = `insert into event_${tableName} values(null,'${username}','${moduleName}','${pageName}','${eventName}','${localTime}','${startTime}',null,0,'')`
        connection.query(sql, function (error, results, fields) {
            try {

                if (error) throw error;
                // if (results.affectedRows == 1) {
                //     console.log(`成功添加`)
                // } else {
                //     console.log(`没有添加`)
                // }
                res.send(results)
            } catch (error) {
                console.log("出错17")
            }

        });
    }



})

function delDiancan(req, res) {
    let nowDay = getTimeByTimeZone(8).Format("yyyy-MM-dd");
    let diancanren = req.body["diancanren"]
    console.log(`准备删除${diancanren}点餐信息`)
    connection.query(`delete from user where DATE_FORMAT(riqi,'%Y-%m-%d') = '${nowDay}' and username = '${diancanren}'`, function (error, results, fields) {
        try {

            if (error) throw error;
            if (results.affectedRows == 1) {
                console.log(`成功删除${diancanren}今日点餐信息`)
                getFoodsToClient()
            } else {
                console.log(`没有${diancanren}今日点餐信息`)
            }
            res.send(results)
        } catch (error) {
            console.log("出错18")
        }

    });
}
app.post('/admin/delDiancan', (req, res) => {
    delDiancan(req, res)
})
app.post('/user/delDiancanMe', (req, res) => {
    delDiancan(req, res)
})

var diancan = (req, res, tjtime) => {
    let riqi = tjtime.split(" ")[0]
    // let tjtime = req.body["tjtime"]
    let diancanren = req.body["diancanren"]
    let caipinSelectArr = req.body["caipinSelectArr"]
    let token = req.headers.token;
    let obj = doToken.verifytoken(token)
    console.log(`${diancanren}点餐了${caipinSelectArr}`)
    connection.query(`delete from user where username = '${diancanren}' and  DATE_FORMAT(riqi,'%Y-%m-%d') = '${riqi}'`, function (error, results, fields) {
        connection.query(`insert into user values(null,'${diancanren}','${caipinSelectArr}','${riqi}','${tjtime}','是','${obj.level}','')`, function (error, results, fields) {
            try {

                if (error) throw error;
                getFoodsToClient()
                res.send(results)
            } catch (error) {
                console.log("出错19")
            }
        });
    });
}
app.post('/user/diancan', (req, res) => {
    let nowDay = getTimeByTimeZone(8).Format("yyyy-MM-dd");
    connection.query(`select id,DATE_FORMAT(riqi,'%Y-%m-%d') as riqi,DATE_FORMAT(startTime,'%Y-%m-%d %T') as startTime,DATE_FORMAT(endTime,'%Y-%m-%d %T') as endTime,caipin,faburen,DATE_FORMAT(tjTime,'%Y-%m-%d %T') as tjTime,remark from detail   where riqi = '${nowDay}' order by id desc LIMIT 1`, function (error, results, fields) {
        try {

            if (error) throw error;
            let bjTime = getTimeByTimeZone(8).Format("yyyy-MM-dd hh:mm:ss")
            let nowTime = new Date(
                bjTime.allReplace("-", "/")
            );
            if (!results.length || !req.body["diancanren"]) {
                //还未发布
                res.send("over")
            }
            else {
                fabuObj = results[0];
                let endTime = new Date(fabuObj.endTime.allReplace("-", "/"));
                let startTime = new Date(fabuObj.startTime.allReplace("-", "/"));
                let daojishi = 0;
                let kedian = false;
                if (nowTime - startTime > 0 && endTime - nowTime > 0) {
                    daojishi = (endTime - nowTime) / 1000;
                    kedian = true;
                } else {
                    kedian = false;
                }
                if (kedian) {
                    diancan(req, res, nowTime.Format("yyyy-MM-dd hh:mm:ss"))
                }
                else {
                    res.send("over")
                }
            }
        } catch (error) {
            console.log("出错20")
        }
    });



})

app.post('/user/getFoods', (req, res) => {
    connection.query(`select * from caipin`, function (error, results, fields) {
        try {

            if (error) throw error;
            res.send(results)
        } catch (error) {
            console.log("出错21")
        }
    });
})

app.post('/user/getYonghu', (req, res) => {
    connection.query(`select * from yonghu`, function (error, results, fields) {
        try {
            let arr = [];
            results.forEach(info => {
                // info.delete("password")
                info["password"] = "";
                info["fabu"] = "";
                arr.push(info)
            });
            if (error) throw error;
            res.send(arr)
        } catch (error) {
            console.log("出错22")
        }
    });
})

app.post('/user/getDiancan', (req, res) => {
    let nowDay = getTimeByTimeZone(8).Format("yyyy-MM-dd");
    console.log(`select username,caipin,DATE_FORMAT(riqi,'%Y-%m-%d') as riqi,tjtime,level from user where riqi = '${nowDay}'`)
    connection.query(`select username,caipin,DATE_FORMAT(riqi,'%Y-%m-%d') as riqi,DATE_FORMAT(tjtime,'%H:%i:%s') as tjtime,level from user where riqi = '${nowDay}'`, function (error, results, fields) {
        try {

            if (error) throw error;
            res.send(results)
        } catch (error) {
            console.log("出错23")
        }
    });
})

app.post('/user/sendRecommend', (req, res) => {
    let recommend = req.body["recommend"];
    recommend.allReplace("/", "\/")
    let token = req.headers.token;
    let obj = doToken.verifytoken(token)
    let username = obj.username
    let nowtime = getTimeByTimeZone(8).Format("yyyy-MM-dd hh:mm:ss");
    connection.query(`insert into recommend values(null,'${username}','${recommend}','${nowtime}','','')`, function (error, results, fields) {
        try {

            if (error) throw error;
            res.send({
                code: 200,
                msg: "",
                data: {
                }
            })
        } catch (error) {
            console.log("出错24")
        }
    })
})

app.post('/user/getFabu', (req, res) => {
    let nowDay = getTimeByTimeZone(8).Format("yyyy-MM-dd");
    connection.query(`select id,DATE_FORMAT(riqi,'%Y-%m-%d') as riqi,DATE_FORMAT(startTime,'%Y-%m-%d %T') as startTime,DATE_FORMAT(endTime,'%Y-%m-%d %T') as endTime,caipin,faburen,DATE_FORMAT(tjTime,'%Y-%m-%d %T') as tjTime,remark from detail   where riqi = '${nowDay}' order by id desc LIMIT 1`, function (error, results, fields) {
        try {

            if (error) throw error;
            res.send(results)
        } catch (error) {
            console.log("出错25")
        }
    });
})

app.get('/user/ceshi', (req, res) => {
    // res.send('Hello World!123')
    connection.query('SELECT * from caipin', function (error, results, fields) {
        try {

            if (error) throw error;
            res.send(results)
        } catch (error) {
            console.log("出错26")
        }
    });
})
var getFoodsToClient = () => {
    let nowDay = getTimeByTimeZone(8).Format("yyyy-MM-dd");
    connection.query(`select *,DATE_FORMAT(tjtime,'%T') as tjtime from user where DATE_FORMAT(riqi,'%Y-%m-%d') = '${nowDay}'`, (error, results, fields) => {
        io.emit("getFoodsToClient", {
            list: results,
            nowDay: nowDay
        })
    })
}
let fabuObj = null
var checkOverTime = (io) => {
    if (fabuObj == null) {
        checkFabuToClient(io)
        setTimeout(() => {
            checkOverTime(io);
        }, 5000)
        return;
    }
    let bjTime = getTimeByTimeZone(8).Format("yyyy-MM-dd hh:mm:ss")
    let nowTime = new Date(
        bjTime.allReplace("-", "/")
    );
    let endTime = new Date(fabuObj.endTime.allReplace("-", "/"));
    let startTime = new Date(fabuObj.startTime.allReplace("-", "/"));
    let daojishi = 0;
    if (startTime > nowTime) {
        //还未开始
        daojishi = (startTime - nowTime) / 1000;
    }
    if (nowTime - startTime > 0 && endTime - nowTime > 0) {
        //还未结束
        daojishi = (endTime - nowTime) / 1000;
    }
    console.log('checkOvernowTime', daojishi * 1000)
    if (daojishi < 0) {
        daojishi = 0;
    }
    setTimeout(() => {
        console.log('开始执行')
        checkFabuToClient(io)
    }, (daojishi + 1) * 1000)
}
var checkOverStatus = () => {
    let nowDay = getTimeByTimeZone(8).Format("yyyy-MM-dd");
    connection.query(`select id,DATE_FORMAT(riqi,'%Y-%m-%d') as riqi,DATE_FORMAT(startTime,'%Y-%m-%d %T') as startTime,DATE_FORMAT(endTime,'%Y-%m-%d %T') as endTime,caipin,faburen,DATE_FORMAT(tjTime,'%Y-%m-%d %T') as tjTime,remark from detail   where riqi = '${nowDay}' order by id desc LIMIT 1`, function (error, results, fields) {
        if (error) throw error;
        let bjTime = getTimeByTimeZone(8).Format("yyyy-MM-dd hh:mm:ss")
        let nowTime = new Date(
            bjTime.allReplace("-", "/")
        );
        if (!results.length) {
            //还未发布
            return false;
        }
        fabuObj = results[0];
        let endTime = new Date(fabuObj.endTime.allReplace("-", "/"));
        let startTime = new Date(fabuObj.startTime.allReplace("-", "/"));
        let daojishi = 0;
        let kedian = false;
        let tishi = ""
        if (nowTime - startTime > 0 && endTime - nowTime > 0) {
            daojishi = (endTime - nowTime) / 1000;
            kedian = true;
        } else {
            kedian = false;
        }
        return kedian;
    });
}
var checkFabuToClient = (io, type) => {
    let nowDay = getTimeByTimeZone(8).Format("yyyy-MM-dd");
    connection.query(`select id,DATE_FORMAT(riqi,'%Y-%m-%d') as riqi,DATE_FORMAT(startTime,'%Y-%m-%d %T') as startTime,DATE_FORMAT(endTime,'%Y-%m-%d %T') as endTime,caipin,faburen,DATE_FORMAT(tjTime,'%Y-%m-%d %T') as tjTime,remark from detail   where riqi = '${nowDay}' order by id desc LIMIT 1`, function (error, results, fields) {
        if (error) throw error;
        let bjTime = getTimeByTimeZone(8).Format("yyyy-MM-dd hh:mm:ss")
        let nowTime = new Date(
            bjTime.allReplace("-", "/")
        );
        if (!results.length) {
            io.emit("checkFabuToClient", {
                fabu: false,
                type: type
            })
            return;
        }
        fabuObj = results[0];
        let endTime = new Date(fabuObj.endTime.allReplace("-", "/"));
        let startTime = new Date(fabuObj.startTime.allReplace("-", "/"));
        let daojishi = 0;
        let kedian = false;
        let tishi = ""
        if (nowTime - startTime > 0 && endTime - nowTime > 0) {
            daojishi = (endTime - nowTime) / 1000;
            kedian = true;
        } else {
            console.log("over");
            if (nowTime - startTime > 0) {
                tishi = `根据最新的发布信息，今天点餐已经结束，下次请早，如需加餐，请联系发布人${fabuObj.faburen}`;
                daojishi = -1;
            } else {
                tishi = `根据最新的发布信息，今天点餐还未开始`;
                daojishi = (startTime - nowTime) / 1000;
            }

            kedian = false;
        }

        io.emit("checkFabuToClient", {
            fabu: true,
            nowTime: nowTime,
            fabuObj: fabuObj,
            daojishi: daojishi,
            kedian: kedian,
            tishi: tishi,
            type: type
        })
        if (daojishi > 0) {
            console.log('checkOverTime2', daojishi * 1000)
            setTimeout(() => {
                checkFabuToClient(io)
            }, (daojishi + 1) * 1000)
        }
        // res.send(results)
    });
}

io.on('connection', socket => {
    checkOverTime(io)
    // 监听客户端发送的信息
    socket.on("reciveClient", message => {
        // 给客户端返回信息
        message += "qin"
        io.emit("sendToClient", {
            message
        });
    });
    // 监听客户端发送的信息
    socket.on("checkFabuToClient", message => {
        checkFabuToClient(io, "");
    });

    // socket.on("getFoodsToClient", message => {
    //     checkFabuToClient(io,message);
    // });
    // 监听连接断开事件
    socket.on("disconnect", (error) => {
        // io.emit("disconnect", "over");
        console.log("连接已断开...");
    });
    socket.on("connect", (error) => {
        // io.emit("disconnect", "over");
        console.log("连接已连接...");
    });
});
server.listen(port_listen, () => console.log(`Example app listening on port ${port_listen} !`))
// var socket = io.listen(server,{origins: '*:*'}); 
// socket.on('connection', function (client) {

//     sys.puts("New client is here!");
//     client.send("hello world");

//     client.on('message', function (msg) { sys.puts("client has sent:" + msg); });
//     client.on('disconnect', function () { sys.puts("Client has disconnected"); });

//     //发送自定义事件
//     client.emit('news', { hello: 'news world' });

//     //临听自定义事件
//     client.on('my other event', function (data) {
//         //console.log(data);
//     });
// });

function getLocalIP() {
    const os = require('os');
    const ifaces = os.networkInterfaces();
    let locatIp = '';
    for (let dev in ifaces) {
        if (dev === 'WLAN') {
            for (let j = 0; j < ifaces[dev].length; j++) {
                if (ifaces[dev][j].family === 'IPv4') {
                    locatIp = ifaces[dev][j].address;
                    break;
                }
            }
        }
    }
    return locatIp;
}

String.prototype.allReplace = function (f, e) { //吧f替换成e
    var reg = new RegExp(f, "g"); //创建正则RegExp对象   
    return this.replace(reg, e);
}
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) :
            (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function getTimeByTimeZone(timeZone) {
    var d = new Date();
    localTime = d.getTime(),
        localOffset = d.getTimezoneOffset() * 60000, //获得当地时间偏移的毫秒数,这里可能是负数
        utc = localTime + localOffset, //utc即GMT时间
        offset = timeZone, //时区，北京市+8  美国华盛顿为 -5
        localSecondTime = utc + (3600000 * offset); //本地对应的毫秒数
    var date = new Date(localSecondTime);
    // console.log("根据本地时间得知" + timeZone + "时区的时间是 " + date.toLocaleString());
    // console.log("系统默认展示时间方式是：" + date)
    return date;
}